#-*- coding: UTF-8 -*-
__author__ = 'Jinkey'
import numpy as np
from sklearn.datasets import load_iris
from matplotlib import pyplot as plt

#加载鸾尾花数据，并读取各属性的值
data = load_iris()
features = data['data']
feature_names = data['feature_names']
target = data['target']
# print feature_names,'\n',features,'\n',target

'''
    建立分类器模型
'''
#对除Setosa以外值进行分类
is_setosa = (target == 0)
features = features[~is_setosa]
label = target[~is_setosa]
virginica = (label == 2)
best_acc = 0
#遍历数组，找出最有的特征和特征阈值
for col in xrange(features.shape[1]):
    #复制当前列向量的元素组成一个新的数组
    row = features[:,col].copy()
    #对得到的数组进行排序
    row.sort()
    #遍历该数组每一个元素
    for r in row:
        #预测值：认为该数组中大于当前值的元素都是virginica
        predict = (features[:, col] > r)
        #实际值：带有人工便签「virginica」的元素

        #在被预测为virginica的值当中，实际是virginica的比例
        # True为1,False为0,均值为所有的判断结果(0，1，1，0,...,1,0,0)求和后
        # 再除以元素个数,也就是值为真(virginica)的比例
        accurate = (predict == virginica).mean()

        #筛选出准确率最高的特征和特征阈值
        if accurate > best_acc:
            best_acc = accurate
            best_col = col
            best_r = r
print best_acc,best_col,best_r

'''
    在图中表示该分类器
'''
#指定参数
br = best_r
p0,p1 = best_col, best_col-1

#填充图表不同分类预测区域的颜色
x0,x1 =[features[:,p0].min()*0.965,features[:,p0].max()*1.035]
y0,y1 =[features[:,p1].min()*0.965,features[:,p1].max()*1.035]
plt.fill_between([br,x1],[y0,y0],[y1,y1],color=(0.2,0.6,0.9,0.3))
plt.fill_between([x0,br],[y0,y0],[y1,y1],color=(0.5,0.3,0.9,0.3))

#绘制散点图和分割线
plt.plot([br,br],[y0,y1],'k--',lw=2,c='g')
plt.scatter(features[virginica,p0], features[virginica,p1], c='b', marker='o',linewidths=0)
plt.scatter(features[~virginica,p0], features[~virginica,p1], c='r', marker='o',linewidths=0)
plt.ylim(y0,y1)
plt.xlim(x0,x1)
plt.xlabel(feature_names[p0])
plt.ylabel(feature_names[p1])
plt.show()